<template>
  <div class='question-container question-new'>
    <el-card class="box-card">
      <!-- 修改与录入都需要使用该组件通过路由信息对象判定是什么操作 -->
      <div slot="header">{{ $route.query.id ? '试题修改' : '试题录入' }}</div>
      <!-- <div slot="header" class="clearfix">
        <span>试题录入</span>
      </div> -->
      <div class="cardBody">
        <el-form ref="containerForm" :model="ctform" :rules="ctRules" label-width="120px">
          <el-form-item label="学科" prop="subjectID">
            <!-- changeSubject 学科改变时需要根据对应的学科去查询 -->
            <el-select v-model="ctform.subjectID" @change="changeSubject" placeholder="请选择">
              <el-option v-for="item in subjectOptions" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录" prop="catalogID">
            <el-select v-model="ctform.catalogID" placeholder="请选择">
              <el-option v-for="item in catalogOptions" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
              <!-- <el-option label="区域一" value="shanghai"></el-option>
              <el-option label="区域二" value="beijing"></el-option> -->
            </el-select>
          </el-form-item>
          <el-form-item label="企业" prop="enterpriseID">
            <el-select v-model="ctform.enterpriseID" style="width:400px">
              <el-option v-for="item in enterpriseOptions" :key="item.id" :label="item.company"
                :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市" prop="city">
            <el-select v-model="ctform.province" @change="getAreaOptions" style="width:198px">
              <el-option v-for="item in cityOptions" :key="item" :label="item" :value="item"></el-option>
            </el-select>
            <el-select v-model="ctform.city" style="width:198px;margin-left:4px">
              <el-option v-for="item in areaOptions" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="方向" prop="direction">
            <el-select v-model="ctform.direction" style="width:400px">
              <el-option v-for="item in directionOptions" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型" prop="questionType">
            <el-radio-group @change="changeRadio({})" v-model="ctform.questionType">
              <el-radio v-for="item in questionType" :key="item.value" :label="item.value + ''">{{
                item.label
              }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度" prop="difficulty">
            <el-radio-group v-model="ctform.difficulty">
              <el-radio v-for="item in difficulty" :key="item.value" :label="item.value + ''">{{
                item.label
              }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 这里需要引入富文本组件  -->
          <!-- npm install vue-quill-editor --save -->
          <!-- editorOptions富文本配置项 -->
          <el-form-item label="题干" prop="question">
            <quill-editor @blur="checkQustion" v-model="ctform.question" :options="toolbarOptions"></quill-editor>
          </el-form-item>
          <!-- 选项部分根据题型需要改变显示 -->
          <!-- 简答不需要选项 -->
          <!-- 单选 redio-->
          <!-- 多选 checkbox -->
          <el-form-item label="选项" prop="options" v-if="ctform.questionType !== '3'">
            <div v-for="item in ctform.options" :key="item.id" class="options">
              <!-- 单选 -->
              <el-radio v-if="ctform.questionType === '1'" @change="changeRadio(item)" v-model="item.isRight"
                :label="true">{{ item.code }}：</el-radio>
              <el-checkbox v-if="ctform.questionType === '2'" v-model="item.isRight" style="margin-right:0"
                :label="true">{{ item.code }}：</el-checkbox>
              <el-input v-model="item.title" style="width:240px"></el-input>
              <!-- jsonplaceholder.typicode.com 免费的HTTP请求假数据接口-->
              <!-- 	action必选参数，上传的地址 -->
              <!-- headers设置上传的请求头部 -->
              <!-- on-success文件上传成功时的钩子 -->
              <!-- show-file-list是否显示已上传文件列表 -->
              <el-upload style="margin-left:4px" class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/" :headers="{ 'Authorization': 'Bearer ' + token }"
                :on-success="(res, file) => { uploadSuccess(item, res, file) }" :show-file-list="true">
                <img v-if="item.img" :src="item.img" class="avatar">
                <span v-else>上传图片</span>
                <i class="el-icon-circle-close"></i>
              </el-upload>
            </div>
            <el-button type="danger" :disabled="ctform.questionType !== '2'" @click="addOption"
              size="small">+增加选项与答案</el-button>
          </el-form-item>
          <el-form-item label="解析视频：">
            <el-input v-model="ctform.videoURL" style="width:400px"></el-input>
          </el-form-item>
          <el-form-item label="答案解析：" prop="question">
            <quill-editor v-model="ctform.answer" :options="toolbarOptions"></quill-editor>
          </el-form-item>
          <el-form-item label="题目备注：">
            <el-input type="textarea" :rows="4" v-model="ctform.remarks" style="width:400px"></el-input>
          </el-form-item>
          <el-form-item label="试题标签：">
            <el-select style="width:400px" v-model="ctform.tags" multiple filterable allow-create default-first-option
              placeholder="请选择试题标签">
              <el-option v-for="item in tagsOptions" :key="item.value" :label="item.label" :value="item.label">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 提交按钮-->
          <el-form-item>
            <!-- 根据路由对象信息显示不同的按钮 -->
            <!-- 修改与录入 -->
            <el-button v-if="!$route.query.id" @click="submit()" type="primary">确认提交</el-button>
            <el-button v-else @click="update()" type="success">确认修改</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
// 学科请求接口
import { simple as getSubjectOptions } from '@/api/hmmm/subjects'
// 目录请求接口
import { simple as getCatalogOptions } from '@/api/hmmm/directorys'
// 标签请求
import { simple as getTagOptions } from '@/api/hmmm/tags'
// 企业管理请求
import { list as getCompanyOptions } from '@/api/hmmm/companys'
// 城市数据
import { provinces as getCityOptions, citys as getAreaOptions } from '@/api/hmmm/citys'
// 富文本编辑器组件局部引入start
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
// 富文本编辑器组件局部引入end
// 数据转换引入
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
// 引入接口
import { add, detail, update } from '@/api/hmmm/questions'
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      token: getToken(),
      direction,
      questionType,
      difficulty,
      // 需要提交的数据 也就是form表单双向绑定
      ctform: {
        // 学科
        subjectID: null,
        // 目录
        catalogID: null,
        // 企业
        enterpriseID: null,
        // 城市
        province: null,
        // 地区
        city: null,
        // 方向
        direction: null,
        // 题型
        questionType: '1',
        // 难度
        difficulty: '1',
        // 题干
        question: null,
        // 选项
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ]
      },
      // 校验规则
      ctRules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ]
      },
      // 富文本配置
      toolbarOptions: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],// 加粗 斜体 下划线 删除线
            [{ list: 'ordered' }, { list: 'bullet' }],// 有序、无序列表
            ['blockquote'], // 引用
            ['code-block', 'image', 'link']//代码块 图片 链接
          ],
        }
      },
      // 学科选项
      subjectOptions: [],
      // 目录选项
      catalogOptions: [],
      // 企业选项
      enterpriseOptions: [],
      // 城市选项 获取城市数据
      cityOptions: getCityOptions(),
      // 地区选项 通过城市数据才能获取对应的地区
      areaOptions: [],
      // 方向选项
      directionOptions: direction,
      // 题型
      questionType,
      // 难度
      difficulty,
      // 标签选项
      tagsOptions: []
    }
  },
  components: {
    quillEditor//富文本编辑器组件
  },
  // 初始化钩子函数
  created() {
    // 请求学科
    this.getSubjectOptions()
    // 请求企业管理列表
    this.getCompanyOptions()
    // 如果路由信息对象存在id 则说明是修改
    // 调用接口获取题目信息
    if (this.$route.query.id) {
      this.getQuestion()
    }
  },
  watch: {//监听路由对象信息变化
    '$route.query': function () {
      // 如果路由信息对象存在id 则说明是修改
      // 调用接口获取题目信息
      if (this.$route.query.id) {
        this.getQuestion()
      } else {
        // 重置表单
        this.ctform = {
          subjectID: null,
          catalogID: null,
          enterpriseID: null,
          province: null,
          city: null,
          direction: null,
          questionType: '1',
          difficulty: '1',
          question: null,
          options: [
            { isRight: false, code: 'A', title: '', img: '' },
            { isRight: false, code: 'B', title: '', img: '' },
            { isRight: false, code: 'C', title: '', img: '' },
            { isRight: false, code: 'D', title: '', img: '' }
          ]
        }
        this.$nextTick(() => {
          // 移除该表单项的校验结果
          this.$refs.containerForm.clearValidate()
        })
      }
    }
  },
  methods: {
    // 获取题目信息
    async getQuestion() {
      // 请求基础题库详情
      const { data } = await detail({ id: this.$route.query.id })
      // 标签数组
      data.tags = data.tags.split(',')
      // 选项
      data.options = data.options.map(item => {
        item.isRight = item.isRight === 1
        return item
      })
      // 将获得数据赋值给表单
      this.ctform = data
      // 根据请求到的数据去请求目录几标签
      const res = await getCatalogOptions({ subjectID: this.ctform.subjectID })
      this.catalogOptions = res.data//目录选项
      const res2 = await getTagOptions({ subjectID: this.ctform.subjectID })
      this.tagsOptions = res2.data//标签选项
    },
    // 当学科发生改变时需要
    async changeSubject(subjectID) {
      this.ctform.catalogID = null//目录置空
      // 请求目录及标签
      const result = await getCatalogOptions({ subjectID: this.ctform.subjectID })
      this.catalogOptions = result.data//目录选项
      this.ctform.tags = null//标签置空
      const result2 = await getTagOptions({ subjectID: this.ctform.subjectID })
      this.tagsOptions = result2.data//标签选项
    },
    // 提交
    submit() {
      // 执行自定义校验
      this.$refs.containerForm.validate(async valid => {
        if (valid) {
          const data = { ...this.ctform }
          data.tags = data.tags.join(',')//将标签数据重新转化为字符串
          await add(data)
          this.$message.success('添加成功')
          this.$router.push('/questions/list')//跳转到组题列表
        }
      })
    },
    update() {//更新操作
      this.$refs.containerForm.validate(async valid => {
        if (valid) {
          const data = { ...this.ctform }
          data.tags = data.tags.join(',')
          await update(data)
          this.$message.success('修改成功')
          this.$router.push('/questions/list')
        }
      })
    },
    // 上传成功
    uploadSuccess(item, res, file) {
      // 上传成功后将地址传给item下的img
      // res 是相应对象
      // file 选择后的文件对象   file.raw 原始文件对象
      // URL.createObjectURL(file.raw)  本地预览地址
      // item 就是当前的选项对象
      item.img = URL.createObjectURL(file.raw)
    },
    // 添加选项
    addOption() {
      // 索引 0 ---> A  ascii  65
      // 索引 1 ---> B  ascii  66
      // 索引 2 ---> C  ascii  67
      // 索引 3 ---> D  ascii  68
      // 索引 4 ---> E  ascii  69
      this.ctform.options.push({
        isRight: false,
        // fromCharCode用于从Unicode 值序列创建字符串
        code: String.fromCharCode(65 + this.ctform.options.length),
        title: '',
        img: ''
      })
    },
    // 选择了题型
    // 选择单选框
    changeRadio(item) {
      // 1. 清除所有的选中
      this.ctform.options.forEach(item => {
        item.isRight = false
      })
      // 2. 自己选中
      item.isRight = true
    },
    // 校验题干
    checkQustion() {
      this.$refs.containerForm.validateField('question')
    },
    //  请求学科
    async getSubjectOptions() {
      const res = await getSubjectOptions()
      this.subjectOptions = res.data
    },
    // 请求企业管理列表
    async getCompanyOptions() {
      const res = await getCompanyOptions({ pagesize: 10000 })
      //res.data.items下拉选项数据id 选项值company选项文字
      this.enterpriseOptions = res.data.items//将企业信息赋值到选项
    },
    getAreaOptions(cityName) {
      // 清空地区选中的值
      this.ctform.city = null
      // cityName 是你选中城市后的值
      this.areaOptions = getAreaOptions(cityName)
    }
  }
}

</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.question-container {
  margin: 10px;

  .cardBody {
    padding: 20px;
  }
}

.question-new ::v-deep .ql-editor {
  height: 200px;
}

.question-new ::v-deep .ql-toolbar.ql-snow {
  padding: 0 8px;
}


// 上传样式
.options {
  padding-bottom: 20px;
}

.avatar-uploader {
  display: inline-block;
  vertical-align: middle;
  line-height: 1;
}

.question-new ::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  width: 100px;
  height: 60px;
  line-height: 60px;
}

.question-new ::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.question-new ::v-deep .avatar-uploader i {
  position: absolute;
  right: 0;
  top: 0;
  transform: translate(50%, -50%);
  background: #fff;
  font-size: 18px;
  color: #999;
}

.avatar {
  width: 100px;
  height: 60px;
  display: block;
  overflow: hidden;
}
</style>
